#include "game.h"
#include "ui_game.h"
#include <QKeyEvent>
#include <QDebug>
#include <QPainter>
#include <QRandomGenerator>



Game::Game(QWidget *parent) : QWidget(parent), score(0) {
    ui->setupUi(this);
    this->resize(1000, 600);


    player = new QMediaPlayer(this);
    audioOutput = new QAudioOutput(this);
    player->setAudioOutput(audioOutput);
    player->setSource(QUrl("qrc:///bgm3.mp3"));
    player->setLoops(QMediaPlayer::Infinite);
    audioOutput->setVolume(20);
    player->play();                     //加载bgm3




    scoreLabel = new QLabel("Score: 0", this);
    scoreLabel->setStyleSheet("font-size: 24px; color: black;");
    fanhui = new QPushButton("Back", this);
    fanhui->setStyleSheet("font-size: 20px; color: pink;");
    connect(fanhui, &QPushButton::clicked, this, &Game::onReturn);     //分数标签和返回按钮


    QHBoxLayout *topLayout = new QHBoxLayout();
    topLayout->addWidget(scoreLabel);
    topLayout->addStretch();     //弹簧
    topLayout->addWidget(fanhui);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(topLayout);
    mainLayout->addStretch();                          //布局


    noteTimer = new QTimer(this);
    connect(noteTimer, &QTimer::timeout, this, &Game::generateNote);
    noteTimer->start(800);                            //音符生成定时器（每800ms生成一个）


    moveTimer = new QTimer(this);
    connect(moveTimer, &QTimer::timeout, this, &Game::moveNotes);
    moveTimer->start(50);                           //音符移动生成器（每50ms更新一次位置）
}

void Game::generateNote() {
    // 4条轨道的固定x坐标（适配100宽度）
    const int trackWidth = width() / 4;
    const int trackPositions[4] = {
        trackWidth / 2 - 50,      // 第1条轨道（100宽度居中：/2 - 50）
        trackWidth + trackWidth / 2 - 50,
        2 * trackWidth + trackWidth / 2 - 50,
        3 * trackWidth + trackWidth / 2 - 50
    };

    // 随机选择一条轨道生成音符（尺寸100x40）
    int trackIndex = QRandomGenerator::global()->bounded(4);
    notes.append(QRect(trackPositions[trackIndex], 0, 100, 40)); // 修改为100x40
    update();
}

void Game::moveNotes() {

    for (int i = 0; i < notes.size(); ++i) {
        notes[i].translate(0, 5);
    }                                      // 移动所有音符（y坐标增加5像素）


    for (int i = notes.size() - 1; i >= 0; --i) {
        if (notes[i].y() > height()) {
            notes.removeAt(i);             // 移除超出屏幕的音符
        }
    }
    update();
}

void Game::paintEvent(QPaintEvent *event) {
    Q_UNUSED(event);
    QPainter painter(this);


    painter.drawPixmap(0, 0, width(), height(), QPixmap(":/bg3.bmp"));        //绘制背景


    painter.setPen(QPen(Qt::blue, 2));
    for (int i = 1; i < 4; ++i) {
        int x = i * width() / 4;
        painter.drawLine(x, 0, x, height());
    }                                //    绘制4条轨道分割线（蓝色竖线）



    painter.drawLine(0, 500, width(), 500);      // 绘制判定线（蓝色横线，y=500）

    // 绘制所有音符（使用100x40图片）
    for (const QRect &note : notes) {
        QPixmap noteImage(":/b/button.bmp");
        if (!noteImage.isNull()) {
            // 缩放图片适配100x40尺寸
            painter.drawPixmap(note, noteImage.scaled(100, 40));
        } else {
            // 备用：蓝色矩形
            painter.fillRect(note, Qt::blue);
        }
    }
}

void Game::keyPressEvent(QKeyEvent *event) {
    // 4条轨道对应的按键：S/F/J/L
    const int trackIndices[4] = {0, 1, 2, 3};
    int pressedTrack = -1;

    switch (event->key()) {
    case Qt::Key_S: pressedTrack = 0; break;
    case Qt::Key_F: pressedTrack = 1; break;
    case Qt::Key_J: pressedTrack = 2; break;
    case Qt::Key_L: pressedTrack = 3; break;                                    //键盘信号
    default: QWidget::keyPressEvent(event); return;
    }

    // 检测是否击中音符（适配100x40尺寸）
    for (int i = 0; i < notes.size(); ++i) {
        int noteTrack = notes[i].x() / (width() / 4);
        if (noteTrack == pressedTrack) {
            // 判断音符底部是否进入判定区（y+40），且顶部未离开判定区（y）
            bool isHit = (notes[i].y() + 40 >= 450) && (notes[i].y() <= 550);
            if (isHit) {
                notes.removeAt(i);
                score += 10;
                scoreLabel->setText(QString("Score: %1").arg(score));
                break;
            }
        }
    }
}

void Game::onReturn() {

    noteTimer->stop();
    moveTimer->stop();

}

Game::~Game() {
    delete player;
    delete audioOutput;
    delete noteTimer;
    delete moveTimer;
    delete fanhui;
    delete ui;
}
